/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kurvykurvy.image;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

/**
 *
 * @author HY
 */
public class JavaImageUtils
{
    public static BufferedImage createThumbnail( BufferedImage image, double scale )
    {
        double aspectRatio = (double) image.getWidth() / (double) image.getHeight();
        Dimension newSize = new Dimension();
        newSize.width = (int) ( image.getWidth() * scale );
        newSize.height = (int) ( image.getHeight() * scale );

        System.out.println( "Original Size : " + image.getWidth() + ", " + image.getHeight() );
        System.out.println( "Aspect Ratio : " + aspectRatio );
        System.out.println( "Scale : " + scale );
        System.out.println( "New Size : " + newSize.width + ", " + newSize.height );
        if( image.getHeight() < image.getWidth() &&
            newSize.height < 600 )
        {
            newSize.height = 600;
            newSize.width = (int) ( 600 * aspectRatio );
        }
        else if( image.getHeight() > image.getWidth() &&
                 newSize.width < 600 )
        {
            newSize.width = 600;
            newSize.height = (int) ( 600 / aspectRatio );
        }
        System.out.println( "Adjusted New Size : " + newSize.width + ", " + newSize.height );
        
        BufferedImage thumbnail = new BufferedImage( newSize.width, newSize.height, BufferedImage.TYPE_INT_RGB );

        Graphics2D g2 = thumbnail.createGraphics();
        g2.drawImage( image.getScaledInstance( newSize.width, newSize.height, Image.SCALE_SMOOTH ), null, null );
        g2.dispose();

        return thumbnail;
    }

    public static BufferedImage createThumbnail( BufferedImage image, int requestedThumbSize )
    {
        float ratio = (float) image.getWidth() / (float) image.getHeight();
        int width = image.getWidth();
        BufferedImage thumb = image;

        do
        {
            width /= 2;
            if ( width < requestedThumbSize )
            {
                width = requestedThumbSize;
            }

            BufferedImage temp = new BufferedImage( width, (int) (width / ratio), BufferedImage.TYPE_INT_ARGB );
            Graphics2D g2 = temp.createGraphics();
            g2.setRenderingHint( RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR );
            g2.drawImage( thumb, 0, 0, temp.getWidth(), temp.getHeight(), null );
            g2.dispose();

            thumb = temp;
        }
        while ( width != requestedThumbSize );

        return thumb;
    }
}
